package com.system.demo.commonService.impl;

import com.system.demo.commonService.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.*;

import static com.system.demo.service.constant.MailConstant.SET_EMAIL_ADDRESS_TEMPLATE_PATH;

@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private SpringTemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;


    @Override
    public Boolean sendMail(String emailReceiver, String subject, String templatePath, Map<String, Object> variables) throws MessagingException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        try {
            // 设置邮件发送者、接收者和主题
            helper.setFrom(from);
            helper.setTo(emailReceiver);
            helper.setSubject(subject);

            // 处理模板内容
            String emailContent = processTemplate(templatePath, variables);
            helper.setText(emailContent, true);

            // 发送邮件
            javaMailSender.send(message);
            return true; // 发送成功
        } catch (MessagingException | MailException e) {
            e.printStackTrace();
            return false; // 发送失败
        }
    }

    @Override
    public Boolean sendBindingMail(String emailReceiver, String subject, String bindingLink) {


        // 准备邮件内容的变量
        Map<String, Object> variables = new HashMap<>();
        variables.put("link", bindingLink);  // 在模板中会引用这个变量

        // 使用邮件模板发送邮件
        try {
            return sendMail(emailReceiver, subject, SET_EMAIL_ADDRESS_TEMPLATE_PATH, variables);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    private String processTemplate(String templatePath, Map<String, Object> variables) {
        Context context = new Context();
        // 将变量放入 Thymeleaf 上下文
        if (variables != null) {
            variables.forEach(context::setVariable);
        }
        return templateEngine.process(templatePath, context);
    }

}
